package com.security.hikapp.network;


import static com.security.hikapp.network.Api.BASE_URL;

import android.util.Log;


import com.security.hikapp.utils.SharedPreUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * 使用Hilt进行依赖进入:
 * 第一步：定义Application，并在AndroidManifest.xml中注册
 * 第二步：@InstallIn(ApplicationComponent.class)
 * 第三步：创建单例对象
 * 第四步：在需要使用retrofit的🥱中配置 @AndroidEntryPoint，用于声明该类可以通过Hilt注入
 */
@InstallIn(ApplicationComponent.class)
@Module
public class NetworkModule {

    private static int TIME_OUT = 60 * 5; //5分钟超时断开连接

    @Singleton
    @Provides
    OkHttpClient provideOkHttpClient(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    String s = message.toString().replaceAll("%(?![0-9a-fA-F]{2})", "%25").replaceAll("\\+", "%2B");
                    Log.d("TAG", URLDecoder.decode(s, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor interceptor1 = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Authorization", SharedPreUtil.getString("token"));
                return chain.proceed(builder.build());
            }
        };

        return new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(interceptor1)
                .build();
    }

    @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client){
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())//用于@body注解以及指定返回的数据类型
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())//用于支持rxjava
                .build();
    }

    @Singleton
    @Provides
    ApiService provideApiService(Retrofit retrofit){
        return retrofit.create(ApiService.class);
    }
}
